package com.zrx.app.android.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.zrx.app.android.R;
import com.zrx.app.android.UTIL.RemoteConn;
import com.zrx.app.android.UTIL.ZRXUTIL;
import com.zrx.app.android.ZRXApplication;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * Created by liuji on 2017/4/14.
 *
 * 获取照片独立的fragment
 */

public class ImageFrag extends BaseFragment {
    private static final String TAG = "ImageFrag";

    ImageView imgView = null;
    View takePhoto = null;
    View pickPhoto = null;
    TextView label_keyName = null;
    TextView label_description = null;

    String photoPath = "";
    String photoRawPath = "";

    @Override
    public void initParams(JSONObject node, String key, String dir) {
        super.initParams(node, key, dir);
        this.photoPath = dir + "/" + key + ".jpg";
        this.photoRawPath = dir + "/" + key + ".raw.jpg";
    }

    @Override
    public void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);
        if (!isInited) {
            TypedArray props = context.obtainStyledAttributes(attrs, R.styleable.com_zrx_app_android_fragment_ImageFrag);
            dir = ZRXUTIL.path + props.getString(R.styleable.com_zrx_app_android_fragment_ImageFrag_dir);
            key = props.getString(R.styleable.com_zrx_app_android_fragment_ImageFrag_key);
            photoPath = dir + "/" + key + ".jpg";
            photoRawPath = dir + "/" + key + ".raw.jpg";
            node = new JSONObject();
            isInited = true;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        final View _view = inflater.inflate(R.layout.layout_image, container, false);
        try {
            label_keyName = (TextView) _view.findViewById(R.id.label_keyName);
            label_description = (TextView) _view.findViewById(R.id.label_description);
            imgView = (ImageView) _view.findViewById(R.id.img_photo);
            takePhoto = _view.findViewById(R.id.btn_takePhoto);
            pickPhoto = _view.findViewById(R.id.btn_pickPhoto);

            label_keyName.setText(key);
            if (node.containsKey("policy"))
                label_description.setText(node.getJSONArray("policy").toJSONString());
            else
                label_description.setText("");

            loadPhoto(imgView);

            imgView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final Dialog nagDialog = new Dialog(v.getContext(), android.R.style.Theme_Material_NoActionBar_Fullscreen);
                    nagDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    nagDialog.setCancelable(false);
                    nagDialog.setContentView(R.layout.image_view_fullscreen);

                    ImageView ivPreview = (ImageView) nagDialog.findViewById(R.id.iv_preview_image);

                    try {
                        File photoFile = new File(photoPath);
                        if (!photoFile.exists() && node.containsKey("val"))
                            photoFile = new File(ZRXUTIL.getCachePath() + "/" + node.getString("val"));
                        if (!photoFile.exists())
                            return;
                        ivPreview.setImageURI(Uri.fromFile(photoFile));
                    } catch (Exception e) {
                        ivPreview.setImageResource(R.drawable.loading_black);
                    }

                    ivPreview.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            nagDialog.dismiss();
                        }
                    });
                    nagDialog.show();
                }
            });

            final String _dir = dir;
            takePhoto.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    File dir = new File(_dir);
                    if (!dir.exists())
                        dir.mkdirs();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(photoRawPath)));

                    startActivityForResult(takePictureIntent, ZRXUTIL.REQ_TAKE_PHOTO);
                }
            });


            pickPhoto.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    File dir = new File(_dir);
                    if (!dir.exists())
                        dir.mkdirs();
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "从本地选择"), ZRXUTIL.REQ_LOCAL_PHOTO);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return _view;
    }

    class ImageAsyncTask extends AsyncTask {
        String fileId;

        @Override
        protected Object doInBackground(Object[] params) {
            try {
                fileId = (String) params[1];
                return RemoteConn.getInstance().getFile(fileId, ZRXUTIL.getCachePath() + "/" + fileId);
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
            return false;
        }

        @Override
        protected void onPostExecute(Object o) {
            try {
                if (Boolean.TRUE.equals(o))
                    imgView.setImageBitmap(fitToImageView(ZRXUTIL.getCachePath() + "/" + fileId));
                else
                    imgView.setImageResource(R.drawable.fail);
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        }
    }

    ;

    private void loadPhoto(ImageView iv) {
        final File photoFile = new File(photoPath);
        if (photoFile.exists()) {
            //iv.setImageResource(R.drawable.loading_black);
            iv.setImageBitmap(fitToImageView(photoPath));
            return;
        } else if (node.containsKey("val")) {
            String fileId = node.getString("val");
            File cacheFile = new File(ZRXUTIL.getCachePath() + "/" + fileId);
            if (cacheFile.exists()) {
                iv.setImageBitmap(fitToImageView(cacheFile.getAbsolutePath()));
            } else {
                iv.setImageResource(R.drawable.loading_black);
                ImageAsyncTask iat = new ImageAsyncTask();
                iat.execute(AsyncTask.THREAD_POOL_EXECUTOR, fileId);
            }
        } else {
            iv.setImageResource(R.drawable.id_photo);
        }
    }

    public String getKey() {
        return key;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK)
            try {
                if (requestCode == ZRXUTIL.REQ_TAKE_PHOTO) {

                    File rawFile = new File(photoRawPath);
                    if (rawFile.exists() && rawFile.length() > 1024 * 1024 * 2) {
                        Bitmap compressedBitmap = scaleBitmap(photoRawPath, 900, 600);
                        savaPhotoToLocal(photoPath, compressedBitmap);
                    } else {
                        rawFile.renameTo(new File(photoPath));
                    }
                    node.remove("val");
                    loadPhoto(imgView);
                } else if (requestCode == ZRXUTIL.REQ_LOCAL_PHOTO) {
                    Bitmap rawPhoto = MediaStore.Images.Media.getBitmap(ZRXApplication.getAppContext().getContentResolver(), data.getData());
                    if (rawPhoto.getByteCount() > 1024 * 1024 * 2) {
                        FileOutputStream fos = new FileOutputStream(photoRawPath);
                        final BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);
                        rawPhoto.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        Bitmap compressedBitmap = scaleBitmap(photoRawPath, 900, 600);
                        savaPhotoToLocal(photoPath, compressedBitmap);
                    } else {
                        savaPhotoToLocal(photoPath, rawPhoto);
                    }
                    node.remove("val");
                    loadPhoto(imgView);
                }
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
    }

    private Bitmap fitToImageView(String mCurrentPhotoPath) {
        //int targetW = imgView.getWidth();
        int targetW = (int) getResources().getDimension(R.dimen.img_width);
        //int targetH = imgView.getHeight();
        int targetH = (int) getResources().getDimension(R.dimen.img_height);
        return scaleBitmap(mCurrentPhotoPath, targetW, targetH);
    }

    private Bitmap scaleBitmap(String mCurrentPhotoPath, int targetW, int targetH) {
        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        return bitmap;
    }

    public static void savaPhotoToLocal(String outPath, Bitmap btp) {
        try {
            FileOutputStream fileOut = new FileOutputStream(outPath);
            btp.compress(Bitmap.CompressFormat.JPEG, 100, fileOut);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public String getPhotoPath() {
        return photoPath;
    }

}
